﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Core.Expansion;
using Newtonsoft.Json.Linq;
using Tool.Common;
using Tool.ImageHelper;
using Tool.Web.HttpHelper;
using Tool.Windows.Win32;
using static Core.Common.Global;

namespace Core.Function
{
	public static class BiliBili
	{
		static readonly Random random = new Random();

		/// <summary>
		/// 视频解析
		/// </summary>
		/// <param name="id"></param>
		/// <param name="type">0为aid，1为bvid</param>
		/// <returns></returns>
		public static string AvAndBvParse(string id, int type = 0)
		{
			JObject val;
			string aid, bvid;
			try
			{
				if (type == 0)
					val = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.bilibili.com/x/web-interface/view?aid=" + id)));
				else
					val = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.bilibili.com/x/web-interface/view?bvid=BV" + id)));
			}
			catch (Exception ex)
			{
				return "获取数据失败：" + ex.Message;
			}
			if (val.ContainsKey("code"))
			{
				if (val["code"].ToObject<int>() == 0)
				{
					aid = val["data"]["aid"].ToString();
					bvid = val["data"]["bvid"].ToString();
					string text = Win32Help.IniReadValue(AppDir + "bilibili-通用.ini", "AV解析", "回复", "[封面][换行][up主名称]([up主uid])：[换行][标题][换行][简介][换行]https://www.bilibili.com/video/av[av]", 65535);
					if (text.Contains("[换行]")) text = text.Replace("[换行]", "\r\n");
					if (text.Contains("[封面]"))
					{
						text = text.Replace("[封面]", CQ.Code_Image("少看点二次元\\av_" + aid + ".jpg"));
						File.WriteAllBytes(ImagePath + "av_" + aid + ".jpg", HttpNet.Get(val["data"]["pic"].ToString()));
					}
					if (text.Contains("[av]")) text = text.Replace("[av]", aid);
					if (text.Contains("[bv]")) text = text.Replace("[bv]", bvid);
					if (text.Contains("[标题]")) text = text.Replace("[标题]", val["data"]["title"].ToString());
					if (text.Contains("[简介]")) text = text.Replace("[简介]", val["data"]["desc"].ToString());
					if (text.Contains("[up主名称]")) text = text.Replace("[up主名称]", val["data"]["owner"]["name"].ToString());
					if (text.Contains("[up主uid]")) text = text.Replace("[up主uid]", val["data"]["owner"]["mid"].ToString());
					return text;
				}
				return "获取数据失败：" + val["message"]?.ToString() + "(" + val["code"]?.ToString() + ")";
			}
			return "获取数据失败";
		}

		public static string EpParse(long episode_id)
		{
			try
			{
				JObject jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.imjad.cn/bilibili/?get=source&episode_id=" + episode_id.ToString())));
				if (jObject["code"].ToObject<int>() == 0)
				{
					return AvAndBvParse(jObject["result"][0]["av_id"].ToString(), 0);
				}
				return "获取数据失败：" + jObject["message"]?.ToString() + "(" + jObject["code"]?.ToString() + ")";
			}
			catch (Exception)
			{
				return "获取数据失败";
			}
		}

		public static string MdParse(long media_id)
		{
			JObject jObject;
			try
			{
				jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.bilibili.com/pgc/view/web/media?media_id=" + media_id.ToString())));
			}
			catch (Exception)
			{
				return "获取数据失败";
			}
			if (jObject.ContainsKey("code"))
			{
				if (jObject["code"].ToObject<int>() == 0)
				{
					string text = Win32Help.IniReadValue(AppDir + "bilibili-通用.ini", "MD解析", "回复", "[封面][换行]标题：[标题][换行]原标题：[原标题][换行]开播时间：[开播时间][换行][简介][换行]https://www.bilibili.com/bangumi/media/md[md]", 65535);
					if (text.Contains("[换行]"))
					{
						text = text.Replace("[换行]", "\r\n");
					}
					if (text.Contains("[封面]"))
					{
						text = text.Replace("[封面]", CQ.Code_Image("少看点二次元\\md_" + media_id.ToString() + ".jpg"));
						File.WriteAllBytes(ImagePath + "md_" + media_id.ToString() + ".jpg", HttpNet.Get(jObject["result"]["cover"].ToString()));
					}
					if (text.Contains("[md]"))
					{
						text = text.Replace("[md]", media_id.ToString());
					}
					if (text.Contains("[标题]"))
					{
						text = text.Replace("[标题]", jObject["result"]["title"].ToString());
					}
					if (text.Contains("[原标题]"))
					{
						text = text.Replace("[原标题]", jObject["result"]["origin_name"].ToString());
					}
					if (text.Contains("[简介]"))
					{
						text = text.Replace("[简介]", jObject["result"]["evaluate"].ToString());
					}
					if (text.Contains("[staff]"))
					{
						text = text.Replace("[staff]", jObject["result"]["staff"].ToString());
					}
					if (text.Contains("[角色声优]"))
					{
						text = text.Replace("[角色声优]", jObject["result"]["actors"].ToString());
					}
					if (text.Contains("[开播时间]"))
					{
						text = text.Replace("[开播时间]", jObject["result"]["publish"]["release_date_show"].ToString());
					}
					return text;
				}
				return "获取数据失败：" + jObject["message"]?.ToString() + "(" + jObject["code"]?.ToString() + ")";
			}
			return "获取数据失败";
		}

		public static string SsParse(long season_id)
		{
			try
			{
				JObject jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.imjad.cn/bilibili/?get=seasoninfo&season_id=" + season_id.ToString())));
				if (jObject["code"].ToObject<int>() == 0)
				{
					return MdParse(jObject["result"]["media"]["media_id"].ToObject<int>());
				}
				return "获取数据失败：" + jObject["message"]?.ToString() + "(" + jObject["code"]?.ToString() + ")";
			}
			catch (Exception)
			{
				return "获取数据失败";
			}
		}

		public static bool CreateBiliGif(int aid, out string errormessage)
		{
			errormessage = string.Empty;
			JObject jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.bilibili.com/pvideo?type=jsonp&aid=" + aid.ToString())));
			if (jObject.ContainsKey("code") && jObject["code"].ToObject<int>() == 0)
			{
				GifWriter val = new GifWriter(ImagePath + aid.ToString() + ".gif", 200, 0);
				int num = 0;
				int num2 = jObject["data"]["index"].Count();
				for (int i = 0; i < jObject["data"]["image"].Count(); i++)
				{
					try
					{
						byte[] buffer = HttpNet.Get("http:" + jObject["data"]["image"][i.ToString()]?.ToString());
						int num3 = 160;
						int num4 = 90;
						Bitmap bitmap = new Bitmap(new MemoryStream(buffer));
						decimal d = Math.Ceiling(bitmap.Height / (decimal)num4);
						decimal d2 = Math.Ceiling(bitmap.Width / (decimal)num3);
						decimal d3 = default;
						while (d3 < d)
						{
							decimal d4 = default;
							while (true)
							{
								if (!(d4 < d2))
								{
									++d3;
									break;
								}
								Bitmap bitmap2 = new Bitmap(num3, num4);
								int num5 = 0;
								while (true)
								{
									if (num5 >= num3)
									{
										num++;
										val.WriteFrame(bitmap2, 0);
										++d4;
										break;
									}
									int num6 = 0;
									while (true)
									{
										if (num6 >= num4)
										{
											num5++;
											break;
										}
										if (d4 * num3 + num5 < bitmap.Width && d3 * num4 + num6 < bitmap.Height)
										{
											if (num >= num2)
											{
												goto break_0;
											}
											bitmap2.SetPixel(num5, num6, bitmap.GetPixel((int)(d4 * num3 + num5), (int)(d3 * num4 + num6)));
										}
										num6++;
									}
								}
							}
						}
					}
					catch (Exception ex)
					{
						errormessage = ex.Message;
						return false;
					}
					continue;
				break_0:
					break;
				}
				val.Dispose();
				if (File.Exists(CQ.GetAppFolder() + "gifsicle.exe"))
				{
					string tempFileName = Path.GetTempFileName();
					ProcessStartInfo obj = new ProcessStartInfo
					{
						FileName = CQ.GetAppFolder() + "gifsicle.exe",
						WindowStyle = ProcessWindowStyle.Hidden
					};
					File.Copy(ImagePath + aid.ToString() + ".gif", tempFileName, overwrite: true);
					File.Delete(ImagePath + aid.ToString() + ".gif");
					obj.Arguments = string.Format("-O3 \"{0}\" -o \"{1}\"", tempFileName, ImagePath + aid.ToString() + ".gif");
					Process.Start(obj).WaitForExit();
					File.Delete(tempFileName);
				}
				return true;
			}
			if (jObject.ContainsKey("message"))
			{
				errormessage = jObject["message"].ToString();
			}
			return false;
		}

		public static bool GetCosHot(out string content)
		{
			content = string.Empty;
			string @string = Encoding.UTF8.GetString(HttpNet.Get($"https://api.vc.bilibili.com/link_draw/v2/Photo/list?category=cos&type=hot&page_num={random.Next(0, 15)}&page_size=20"));
			if (string.IsNullOrWhiteSpace(@string))
			{
				return false;
			}
			JObject jObject;
			try
			{
				jObject = JObject.Parse(@string);
			}
			catch (Exception)
			{
				return false;
			}
			if (jObject["code"].ToObject<int>() == 0)
			{
				JToken jToken = jObject["data"]["items"];
				if (jToken.Count() == 0)
				{
					return false;
				}
				int num = random.Next(0, jToken.Count() - 1);
				JToken jToken2 = jToken[num]["item"]["pictures"];
				List<string> str = new List<string>();
				Task.Run(async () =>
				{
					List<Task> tasks = new List<Task>();
					for (int i = 0; i < jToken2.Count(); i++)
					{
						var imgUrl = jToken2[i]["img_src"].ToString();
						await Task.Delay(5);
						var task = Task.Run(() =>
						{
							string text = ImagePath + TimeHelp.GetCurrentTimeUnix(IsMilliseconds: true).ToString() + ".jpg";
							byte[] array = HttpNet.Get(imgUrl);
							if (array.Length != 0)
							{
								File.WriteAllBytes(text, array);
								str.Add(CQ.Code_Image(text.HandleImage().HandleImagePath()));
							}
						});
						tasks.Add(task);
					}
					Task.WaitAll(tasks.ToArray());
				}).Wait();
				content = string.Join(string.Empty, str);
				return true;
			}
			return false;
		}

		public static string GetName(long uid)
		{
			try
			{
				return JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.bilibili.com/x/web-interface/card?mid=" + uid.ToString())))["data"]["card"]["name"].ToString();
			}
			catch (Exception)
			{
				return string.Empty;
			}
		}
	}
}